package com.eastfair.projectcore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;

import com.eastfair.model.TenantRuleVO;
import com.eastfair.projectcore.dao.TenantRuleMapper;
import com.eastfair.projectcore.entity.Menu;
import com.eastfair.projectcore.entity.ProjectDb;
import com.eastfair.projectcore.entity.TenantRule;
import com.eastfair.projectcore.service.TenantRuleService;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

//import com.baomidou.dynamic.datasource.annotation.DS;

/**
 * <p>
 * 业务实现类
 * 租户规则表（合并数据用）
 * </p>
 *
 * @author ligang
 * @date 2022-07-12
 */
@Slf4j
@Service
public class TenantRuleServiceImpl extends SuperServiceImpl<TenantRuleMapper, TenantRule> implements TenantRuleService {

    @Autowired
    SnowFlakeRole snowFlakeRole;
    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<TenantRule> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(TenantRule model) {
        model.setId(snowFlakeRole.findUidSimple());
        //雪花ID,不需要分库分表
        model.setProjectId(ContextUtil.getProjectId());
        return R.successDef();
    }


    @Override
    public R executeTenantTable(List<Long> subSystemIds, String tableName) {
        //查询数据是否存在，存在则沿用合并id
        QueryWrapper<TenantRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(TenantRule::getSystemId, subSystemIds);
        queryWrapper.lambda().eq(TenantRule::getIsDeleted, BusinessConstant.DELETE_NO);
        queryWrapper.lambda().eq(TenantRule::getProjectId, ContextUtil.getProjectId());
        List<TenantRule> tenantRuleList = list(queryWrapper);
//        Long mergeId = DefaultUidGenerator.getUidOfProjectId(ContextUtil.getProjectId());
//        if (tenantRuleList == null || tenantRuleList.isEmpty()) {
//            addData(subSystemIds, tableName, mergeId);
//
//        } else {
//            mergeId = tenantRuleList.get(0).getMergeId();
//            subSystemIds.removeAll(tenantRuleList.stream().map(TenantRule::getSystemId).collect(Collectors.toList()));
//            addData(subSystemIds, tableName, mergeId);
//        }
        return null;
    }

    public void addData(List<Long> subSystemIds, String tableName, Long mergeId) {
        if (subSystemIds == null || subSystemIds.isEmpty()) {
            return;
        }
        for (Long systemId : subSystemIds) {
            TenantRule tenantRule = new TenantRule();
            tenantRule.setSystemId(systemId);
            tenantRule.setTableName(tableName);
            tenantRule.setMergeId(mergeId);
            save(tenantRule);
        }
    }

    @Override
    public R<List<TenantRuleVO>> queryTenantTable() {
        List<TenantRuleVO> tenantRuleVOList = new ArrayList<>();
        QueryWrapper<TenantRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TenantRule::getIsDeleted, BusinessConstant.DELETE_NO);
        queryWrapper.lambda().eq(TenantRule::getProjectId, ContextUtil.getProjectId());
        List<TenantRule> tenantRuleList = list(queryWrapper);
        if (tenantRuleList == null || tenantRuleList.isEmpty()) {
            return R.success(null);
        }
        for (TenantRule tenantRule : tenantRuleList) {
            TenantRuleVO tenantRuleVO = new TenantRuleVO();
            BeanUtils.copyProperties(tenantRule, tenantRuleVO);
            tenantRuleVO.setId(tenantRule.getId());
            tenantRuleVOList.add(tenantRuleVO);
        }
        return R.success(tenantRuleVOList);
    }
}
